package com.ice.body.socket;

import com.ice.base.util.RedisUtil;
import com.ice.body.business.model.ReagentStock;
import com.ice.body.business.service.ReagentStockService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class QRSocketServer {

    @Resource
    private ReagentStockService reagentStockService;
    @Resource
    private RedisUtil redisUtil;

    private ExecutorService pool=null;

/*    public static void main(String[] args) {
        int port = 7001;
        QRSocketServer server = new QRSocketServer();
        server.startServer(port);
    }*/


    public void startServer(int port){
        ServerSocket serverSocket = null;
        //pool =  ThreadPoolUtil.getThreadPool();
        pool = Executors.newFixedThreadPool(2);
        try{
            //bind and listen port
            serverSocket = new ServerSocket(port);
            System.out.println("QRSocketServer bind port: " + port);

            while(true){
                //accept
                Socket clientSocket = null;
                System.out.println("waiting connection...");
                clientSocket = serverSocket.accept();
                System.out.println("New connection accepted " + clientSocket.getInetAddress() + ":" + clientSocket.getPort());
                QRSocketServer.InnerThread innerThread = new QRSocketServer.InnerThread(clientSocket);
                pool.execute(innerThread);
            }
        }catch(Exception e){
            e.printStackTrace();
            pool.shutdown();
        }
    }


    private class InnerThread implements Runnable{
        private Socket clientSocket = null;

        public InnerThread(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        public void run() {
            //accept connection and communicate
            String buf = null;
            BufferedReader br = null;
            PrintWriter pw = null;

            try {
                br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                pw = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

                System.out.println("client ip and port: " + clientSocket.getInetAddress().toString() + ":"+clientSocket.getPort());
                System.out.println("ready");

                //read
                while(true){
                    buf = br.readLine();
                    System.out.println(Thread.currentThread().getName()+" client: " + buf);

                    if(buf.equals("close")){
                        break;
                    }
                    String s = clientSocket.getInetAddress().toString();
                    System.out.println("读取客户端地址:"+ s.substring(1,s.length())+  ",消息,"+buf);
                    //write
                    receiveRfidData(s.substring(1,s.length()),buf);
                    pw.println("response");
                    pw.flush();
                }

                //close
                System.out.println("close client");
                br.close();
                pw.close();
                clientSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }



    public void receiveRfidData(String ip ,String epcCode) {



        System.out.println("接收QR扫描：ip：" + ip + ",epcCode=" + epcCode);
        String warehouseId = "1";

        ReagentStock stockModel = reagentStockService.getByEpcCode(epcCode);
        if (null == stockModel) {
            List<ReagentStock> rkList = redisUtil.get(warehouseId + "rkList") == null ? new ArrayList<>() : (ArrayList) redisUtil.get(warehouseId + "rkList");   //入库
            for (ReagentStock l : rkList) {
                if (l.getEpcCode().equals(epcCode)) {
                    System.out.println("入库重复扫描标签：" + epcCode);
                    return;
                }
            }
            ReagentStock epcModel = reagentStockService.getByEpcCode(epcCode);
            epcModel.setState("0");
            rkList.add(epcModel);
            redisUtil.set(warehouseId + "rkList", rkList);
        } else if (stockModel.getState().equals("2")) {
            List<ReagentStock> ghList = redisUtil.get(warehouseId + "ghList") == null ? new ArrayList<>() : (ArrayList) redisUtil.get(warehouseId + "ghList");   //归还
            for (ReagentStock l : ghList) {
                if (l.getEpcCode().equals(epcCode)) {
                    System.out.println("归还重复扫描标签：" + epcCode);
                    return;
                }
            }
            ReagentStock epcModel = reagentStockService.getByEpcCode(epcCode);
            ghList.add(epcModel);
            epcModel.setState("2");//归还
            redisUtil.set(warehouseId + "ghList", ghList);
        } else if (stockModel.getState().equals("1")) {
            List<ReagentStock> ckList = redisUtil.get(warehouseId + "ckList") == null ? new ArrayList<>() : (ArrayList) redisUtil.get(warehouseId + "ckList");   //出库
            for (ReagentStock l : ckList) {
                if (l.getEpcCode().equals(epcCode)) {
                    System.out.println("出库重复扫描标签：" + epcCode);
                    return;
                }
            }
            ReagentStock epcModel = reagentStockService.getByEpcCode(epcCode);
            epcModel.setState("1");//出库
         //   epcModel.setIfOut("1");//默认出库
            ckList.add(epcModel);
            redisUtil.set(warehouseId + "ckList", ckList);
        }
    }

}
